import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import path from 'path';
import fs from 'fs';
import { Logger } from '../utils/logger.js';
import { ErrorHandler } from '../utils/errorHandler.js';
import { SessionLog } from '../utils/sessionLog.js';

const sessionLog = new SessionLog();

export async function fileTransferMenu(sftpClient, configManager, config) {
  let shouldExit = false;
  let currentRemotePath = '/';

  sessionLog.logConnection(config);

  while (!shouldExit) {
    Logger.separator();

    const { action } = await inquirer.prompt([
      {
        type: 'list',
        name: 'action',
        message: `当前远程目录: ${currentRemotePath}`,
        choices: [
          {
            name: '📤 上传文件',
            value: 'upload',
          },
          {
            name: '📥 下载文件',
            value: 'download',
          },
          {
            name: '📂 浏览文件',
            value: 'browse',
          },
          new inquirer.Separator(),
          {
            name: '❌ 断开连接',
            value: 'disconnect',
          },
        ],
      },
    ]);

    try {
      switch (action) {
        case 'upload':
          await uploadFile(sftpClient, currentRemotePath);
          break;
        case 'download':
          await downloadFile(sftpClient, currentRemotePath);
          break;
        case 'browse':
          currentRemotePath = await browseRemote(sftpClient, currentRemotePath);
          break;
        case 'disconnect':
          Logger.info('正在断开连接...');
          sessionLog.logDisconnection();
          shouldExit = true;
          break;
      }
    } catch (error) {
      const errorMsg = ErrorHandler.handleAndLog(error, 'fileTransferMenu');
      sessionLog.logError(action, error);
    }
  }
}

async function uploadFile(sftpClient, currentPath) {
  Logger.separator();
  const { localFile } = await inquirer.prompt([
    {
      type: 'input',
      name: 'localFile',
      message: '请输入本地文件路径',
      validate: (input) => {
        if (!input) return '文件路径不能为空';
        try {
          ErrorHandler.validatePath(input);
          if (!fs.existsSync(input)) return '本地文件不存在';
          return true;
        } catch (error) {
          return error.message;
        }
      },
    },
  ]);

  const { remotePath } = await inquirer.prompt([
    {
      type: 'input',
      name: 'remotePath',
      message: '请输入远程文件路径 (或只输入文件名保存到当前目录)',
      default: path.basename(localFile),
      validate: (input) => {
        if (!input) return '路径不能为空';
        try {
          ErrorHandler.validatePath(input);
          return true;
        } catch (error) {
          return error.message;
        }
      },
    },
  ]);

  const fullRemotePath = remotePath.startsWith('/') ? remotePath : path.join(currentPath, remotePath).replace(/\\/g, '/');
  const startTime = Date.now();

  const spinner = ora('上传中...').start();
  try {
    const stats = fs.statSync(localFile);
    await sftpClient.uploadFile(localFile, fullRemotePath);
    
    const duration = Date.now() - startTime;
    sessionLog.logUpload(localFile, fullRemotePath, stats.size, duration);
    spinner.succeed('上传成功');
  } catch (error) {
    spinner.fail('上传失败');
    const msg = ErrorHandler.handleFileOperationError(error, '上传');
    Logger.error(msg);
    sessionLog.logError('upload', error);
  }
  Logger.separator();
}

async function downloadFile(sftpClient, currentPath) {
  Logger.separator();
  const { remotePath } = await inquirer.prompt([
    {
      type: 'input',
      name: 'remotePath',
      message: '请输入远程文件路径',
      validate: (input) => {
        if (!input) return '文件路径不能为空';
        try {
          ErrorHandler.validatePath(input);
          return true;
        } catch (error) {
          return error.message;
        }
      },
    },
  ]);

  const { localPath } = await inquirer.prompt([
    {
      type: 'input',
      name: 'localPath',
      message: '请输入本地保存路径 (或只输入文件名保存到当前目录)',
      default: path.basename(remotePath),
      validate: (input) => {
        if (!input) return '路径不能为空';
        try {
          ErrorHandler.validatePath(input);
          return true;
        } catch (error) {
          return error.message;
        }
      },
    },
  ]);

  // 处理本地路径 - 如果是相对路径，则相对于当前工作目录
  const normalizedLocalPath = path.isAbsolute(localPath) ? localPath : path.resolve(process.cwd(), localPath);
  
  // 确保目标目录存在
  const targetDir = path.dirname(normalizedLocalPath);
  if (!fs.existsSync(targetDir)) {
    try {
      fs.mkdirSync(targetDir, { recursive: true });
      Logger.info(`已创建目录: ${targetDir}`);
    } catch (error) {
      Logger.error(`无法创建目录: ${targetDir}`);
      Logger.error(`错误: ${error.message}`);
      return;
    }
  }

  const startTime = Date.now();
  const spinner = ora('下载中...').start();
  try {
    const fullRemotePath = remotePath.startsWith('/') ? remotePath : path.join(currentPath, remotePath).replace(/\\/g, '/');
    
    // 获取文件大小
    const fileInfo = await sftpClient.getFileInfo(fullRemotePath);
    
    await sftpClient.downloadFile(fullRemotePath, normalizedLocalPath);
    
    const duration = Date.now() - startTime;
    sessionLog.logDownload(fullRemotePath, normalizedLocalPath, fileInfo.size, duration);
    spinner.succeed('下载成功');
  } catch (error) {
    spinner.fail('下载失败');
    const msg = ErrorHandler.handleFileOperationError(error, '下载');
    Logger.error(msg);
    sessionLog.logError('download', error);
  }
  Logger.separator();
}

async function browseRemote(sftpClient, currentPath) {
  Logger.separator();
  Logger.info(`正在列出 ${currentPath} 目录...`);

  const spinner = ora('加载中...').start();
  try {
    const files = await sftpClient.listFiles(currentPath);
    spinner.succeed('加载成功');

    if (files.length === 0) {
      Logger.warn('目录为空');
      return currentPath;
    }

    const fileChoices = [];

    if (currentPath !== '/') {
      fileChoices.push({
        name: '⬅️  返回上级目录 (..)',
        value: '..',
      });
    }

    files.forEach((file) => {
      const isDir = file.longname.startsWith('d');
      const icon = isDir ? '📁' : '📄';
      const size = isDir ? '' : ` (${formatBytes(file.attrs.size)})`;
      fileChoices.push({
        name: `${icon} ${file.filename}${size}`,
        value: file.filename,
      });
    });

    const { selectedFile } = await inquirer.prompt([
      {
        type: 'list',
        name: 'selectedFile',
        message: '选择文件或目录',
        choices: fileChoices,
        pageSize: 10,
      },
    ]);

    if (selectedFile === '..') {
      const newPath = currentPath.split('/').slice(0, -1).join('/');
      return newPath || '/';
    } else {
      const selectedFileInfo = files.find((f) => f.filename === selectedFile);
      if (selectedFileInfo && selectedFileInfo.longname.startsWith('d')) {
        return (
          (currentPath === '/' ? '' : currentPath) + '/' + selectedFile
        ).replace(/\\/g, '/').replace('//', '/');
      } else {
        Logger.info(`文件: ${selectedFile}`);
        return currentPath;
      }
    }
  } catch (error) {
    spinner.fail('加载失败');
    const msg = ErrorHandler.handleFileOperationError(error, '列出目录');
    Logger.error(msg);
    sessionLog.logError('browse', error);
    return currentPath;
  } finally {
    Logger.separator();
  }
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}
